/*
 * File:   SynchronizedQueue.h
 * Author: henrya
 *
 * Created on June 26, 2009, 10:06 PM
 */

#ifndef _SYNCHRONIZEDQUEUE_H
#define	_SYNCHRONIZEDQUEUE_H

#include <queue>
#include <pthread.h>
#include <stdlib.h>

using std::queue;

template <typename T>
class SynchronizedQueue {
public:
    SynchronizedQueue();
    virtual ~SynchronizedQueue();
    void push(T msg);
    T pop();
    unsigned int size();
//    Message* peek();
private:
    queue<T> queueue;
    pthread_mutex_t classLock;
};

template <typename T>
SynchronizedQueue<T>::SynchronizedQueue() {
    if (pthread_mutex_init(&classLock, NULL) != 0) {
        perror("SynchronizedQueue lock initialization");
        exit(1);
    }
}

template <typename T>
SynchronizedQueue<T>::~SynchronizedQueue() {
    pthread_mutex_destroy(&classLock);
}

template <typename T>
void SynchronizedQueue<T>::push(T msg) {
    pthread_mutex_lock(&classLock);
    queueue.push(msg);
    pthread_mutex_unlock(&classLock);
}

template <typename T>
T SynchronizedQueue<T>::pop() {
    T res = NULL;
    pthread_mutex_lock(&classLock);
    if (!queueue.empty()) {
        res = queueue.front();
        queueue.pop();
    }
    pthread_mutex_unlock(&classLock);
    return res;
}

template <typename T>
unsigned int SynchronizedQueue<T>::size() {
    unsigned int res(0);
    pthread_mutex_lock(&classLock);
    res=queueue.size();
    pthread_mutex_unlock(&classLock);
    return res;
}
#endif	/* _SYNCHRONIZEDQUEUE_H */

